/*

 * Copyright (C) 2021 Huawei Device Co., Ltd.

 * Licensed under the Apache License, Version 2.0 (the "License");

 * you may not use this file except in compliance with the License.

 * You may obtain a copy of the License at

 *

 *     http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */
package com.aries.ui.widget.demo.slice;

import com.aries.ui.util.FindViewUtil;
import com.aries.ui.view.tab.CommonTabLayout;
import com.aries.ui.view.tab.listener.CustomTabEntity;
import com.aries.ui.view.tab.listener.OnTabSelectListener;
import com.aries.ui.view.tab.utils.UnreadMsgUtils;
import com.aries.ui.view.tab.widget.MsgView;
import com.aries.ui.view.title.TitleBarView;
import com.aries.ui.widget.demo.ResourceTable;
import com.aries.ui.widget.demo.module.tab.EventBusAbility;
import com.aries.ui.widget.demo.module.tab.SimpleCardFragment;
import com.aries.ui.widget.demo.module.tab.SimpleFraction;
import com.aries.ui.widget.demo.module.tab.SwitchTabEvent;
import com.aries.ui.widget.demo.module.tab.entity.TabEntity;
import com.aries.ui.widget.demo.util.SizeUtil;

import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.fraction.Fraction;
import ohos.aafwk.ability.fraction.FractionAbility;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;

import ohos.agp.components.*;
import ohos.agp.utils.Color;
import ohos.agp.window.dialog.ToastDialog;
import ohos.agp.window.service.WindowManager;

import ohos.app.Context;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.security.SecureRandom;

import java.util.ArrayList;

 /**
  * CommonTabAbilitySlice
  */
 public class CommonTabAbilitySlice extends AbilitySlice {
    SecureRandom mRandom = new SecureRandom();
    private Context mContext = this;
    private ArrayList<Component> mFragments = new ArrayList<>();
    private ArrayList<Fraction> mFragments2 = new ArrayList<>();
    private String[] mTitles = {"首页", "消息", "联系人", "更多"};
    private int[] mIconUnSelectIds = {
            ResourceTable.Media_tab_home_unselect, ResourceTable.Media_tab_speech_unselect,
            ResourceTable.Media_tab_contact_unselect, ResourceTable.Media_tab_more_unselect};
    private int[] mIconSelectIds = {
            ResourceTable.Media_tab_home_select, ResourceTable.Media_tab_speech_select,
            ResourceTable.Media_tab_contact_select, ResourceTable.Media_tab_more_select};
    private ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();
    private ScrollView mDecorView;
    private PageSlider mViewPager;
    private CommonTabLayout mTabLayout_1;
    private CommonTabLayout mTabLayout_2;
    private CommonTabLayout mTabLayout_3;
    private CommonTabLayout mTabLayout_4;
    private CommonTabLayout mTabLayout_5;
    private CommonTabLayout mTabLayout_6;
    private CommonTabLayout mTabLayout_7;
    private CommonTabLayout mTabLayout_8;
    private DirectionalLayout mLLayoutContainer;

    //    private EventHandler mHander = new EventHandler();
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_common_tab);
        EventBus.getDefault().register(this);
        initView();
        initTitleBar();
    }

    private void initTitleBar() {
        TitleBarView titleBar = (TitleBarView) findComponentById(ResourceTable.Id_titleBar);
        titleBar.setTitleMainText("CommonTabLayout示例").setOnLeftTextClickListener(component -> terminate());
    }

    @Override
    protected void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    public void initView() {
        getWindow().addFlags(WindowManager.LayoutConfig.MARK_TRANSLUCENT_STATUS);
        for (String title : mTitles) {
            SimpleCardFragment simpleCardFragment = new SimpleCardFragment(getContext());
            simpleCardFragment.setTitle("Switch ViewPager " + title);
            mFragments.add(simpleCardFragment);
            mFragments2.add(SimpleFraction.getInstance(title));
        }

        for (int i = 0; i < mTitles.length; i++) {
            mTabEntities.add(new TabEntity(mTitles[i], mIconSelectIds[i], mIconUnSelectIds[i]));
        }

        mLLayoutContainer = (DirectionalLayout) findComponentById(ResourceTable.Id_lcontainer_common_tab);
        mDecorView = (ScrollView) findComponentById(ResourceTable.Id_scroll);
        mViewPager = FindViewUtil.getTargetView(mDecorView, ResourceTable.Id_vp_2);
        MyPagerAdapter mAdapter = new MyPagerAdapter();
        mViewPager.setProvider(mAdapter);
        /** with nothing */
        mTabLayout_1 = FindViewUtil.getTargetView(mDecorView, ResourceTable.Id_tl_1);
        /** with ViewPager */
        mTabLayout_2 = FindViewUtil.getTargetView(mDecorView, ResourceTable.Id_tl_2);
        /** with Fragments */
        mTabLayout_3 = FindViewUtil.getTargetView(mDecorView, ResourceTable.Id_tl_3);
        /** indicator固定宽度 */
        mTabLayout_4 = FindViewUtil.getTargetView(mDecorView, ResourceTable.Id_tl_4);
        /** indicator固定宽度 */
        mTabLayout_5 = FindViewUtil.getTargetView(mDecorView, ResourceTable.Id_tl_5);
        /** indicator矩形圆角 */
        mTabLayout_6 = FindViewUtil.getTargetView(mDecorView, ResourceTable.Id_tl_6);
        /** indicator三角形 */
        mTabLayout_7 = FindViewUtil.getTargetView(mDecorView, ResourceTable.Id_tl_7);
        /** indicator圆角色块 */
        mTabLayout_8 = FindViewUtil.getTargetView(mDecorView, ResourceTable.Id_tl_8);

        mTabLayout_1.setTabData(mTabEntities);
        tl_2();
        if (getAbility() instanceof FractionAbility) {
            FractionAbility ability = (FractionAbility) getAbility();
            mTabLayout_3.setTabData(mTabEntities, ability.getFractionManager(), ResourceTable.Id_fl_change, mFragments2);
        }
        mTabLayout_4.setTabData(mTabEntities);
        mTabLayout_5.setTabData(mTabEntities);
        mTabLayout_6.setTabData(mTabEntities);
        mTabLayout_7.setTabData(mTabEntities);
        mTabLayout_8.setTabData(mTabEntities);

        mTabLayout_3.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                mTabLayout_1.setCurrentTab(position);
//                mTabLayout_2.setCurrentTab(position);
                mTabLayout_4.setCurrentTab(position);
                mTabLayout_5.setCurrentTab(position);
                mTabLayout_6.setCurrentTab(position);
                mTabLayout_7.setCurrentTab(position);
                mTabLayout_8.setCurrentTab(position);
            }

            @Override
            public void onTabReselect(int position) {

            }
        });
        mTabLayout_8.setCurrentTab(2);
        mTabLayout_3.setCurrentTab(1);

        //显示未读红点
        mTabLayout_1.showDot(2);
        mTabLayout_3.showDot(1);
        mTabLayout_4.showDot(1);

        //两位数
        mTabLayout_2.showMsg(0, 55);
        mTabLayout_2.setMsgMargin(0, -5, 5);

        //三位数
        mTabLayout_2.showMsg(1, 100);
        mTabLayout_2.setMsgMargin(1, -5, 5);

        //设置未读消息红点
        mTabLayout_2.showDot(2);
        MsgView rtv_2_2 = mTabLayout_2.getMsgView(2);
        if (rtv_2_2 != null) {
            UnreadMsgUtils.setSize(rtv_2_2, dp2px(7.5f));
        }

        //设置未读消息背景
        mTabLayout_2.showMsg(3, 5);
        mTabLayout_2.setMsgMargin(3, 0, 5);
        MsgView rtv_2_3 = mTabLayout_2.getMsgView(3);
        if (rtv_2_3 != null) {
            rtv_2_3.setBackgroundColor(Color.getIntColor("#6D8FB0"));
        }
        findComponentById(ResourceTable.Id_btn_eventTab).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component v) {
//                startActivity(new Intent(CommonTabActivity.this, EventBusActivity.class));
                Intent intent = new Intent();
                Operation build = new Intent.OperationBuilder()
                        .withBundleName("com.aries.ui.widget.demo")
                        .withAbilityName(EventBusAbility.class)
                        .build();
                intent.setOperation(build);
                startAbility(intent);
            }
        });

        Image imageView = new Image(mContext);
        imageView.setPixelMap(ResourceTable.Media_icon);

        mTabLayout_1.setCenterView(imageView, SizeUtil.dp2px(36), SizeUtil.dp2px(36), -1, new Component.ClickedListener() {
            @Override
            public void onClick(Component v) {
                new ToastDialog(mContext).setText("点击中间图片").show();
            }
        }).getDelegate().setIndicatorHeight(0);

        mTabLayout_2.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                mViewPager.setCurrentPage(position, false);
//                Toast.makeText(mContext, "onTabSelect:" + position, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onTabReselect(int position) {
//                Toast.makeText(mContext, "onTabReselect:" + position, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void tl_2() {
        mTabLayout_2.setTabData(mTabEntities);
        mTabLayout_2.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                mViewPager.setCurrentPage(position);
            }

            @Override
            public void onTabReselect(int position) {
                if (position == 0) {
                    mTabLayout_2.showMsg(0, mRandom.nextInt(100) + 1);
                }
            }
        });

        mViewPager.addPageChangedListener(new PageSlider.PageChangedListener() {
            @Override
            public void onPageSliding(int i, float v, int i1) {
            }

            @Override
            public void onPageSlideStateChanged(int i) {
            }

            @Override
            public void onPageChosen(int position) {
                mTabLayout_2.setCurrentTab(position);
            }


        });

        mViewPager.setCurrentPage(1);
    }

    protected int dp2px(float dp) {
        return AttrHelper.vp2px(dp, mContext);
    }

    /**
     * 主要演示 刷新上一页面tab时 Fragment 不同时切换问题{@link com.aries.ui.view.tab.utils.FragmentChangeManager#setFragments(int)}
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(SwitchTabEvent event) {
        mTabLayout_3.setCurrentTab(event.getPosition() == mTabLayout_3.getCurrentTab() ? 1 : event.getPosition());
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    private class MyPagerAdapter extends PageSliderProvider {
        @Override
        public int getCount() {
            return mFragments.size();
        }

        @Override
        public Object createPageInContainer(ComponentContainer componentContainer, int i) {
            componentContainer.addComponent(mFragments.get(i));
            return componentContainer;
        }

        @Override
        public void destroyPageFromContainer(ComponentContainer componentContainer, int i, Object o) {
            componentContainer.removeComponent(mFragments.get(i));
        }

        @Override
        public boolean isPageMatchToObject(Component component, Object o) {
            return component == o;
        }

        @Override
        public String getPageTitle(int position) {
            return mTitles[position];
        }
    }
}
